package com.example.back.Controller;

import com.example.back.Annotation.UserLoginToken;
import com.example.back.Entity.Appointment;
import com.example.back.Entity.Auction;
import com.example.back.NonRepEntity.AuctionNowInfo;
import com.example.back.Repository.AppointmentRepository;
import com.example.back.Repository.AuctionRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
    拍卖对应接口，包含预约对应接口
 */
@Slf4j
@RestController
@RequestMapping("auction")
public class AuctionController {
    final int RETURN_PAGE_SIZE = 10;
    @Autowired
    private AuctionRepository auctionRepository;

    @Autowired
    private AppointmentRepository appointmentRepository;

    //预约
    @UserLoginToken
    @PostMapping("/appointment")
    public boolean addNewAppointment(@RequestBody Appointment appointment) {
        try {
            appointment.setAppointmentDate(new Date());
            appointmentRepository.save(appointment);
            appointmentRepository.addAppointment(appointment.getAppointmentAuctionId());
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    //增加新的拍卖
    @UserLoginToken
    @PostMapping("")
    public String addNewAuction(@RequestBody Auction auction) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String d = format.format(auction.getAuctionTimeStamp());
        try {
            auction.setAuctionDate(format.parse(d));
        } catch (ParseException e) {
            e.printStackTrace();
            return "上传失败";
        }
        auction.setNowPrice(auction.getAuctionStartPrice());
        Auction Tauction = auctionRepository.save(auction);
        return Tauction.getAuctionId() + "";
    }

    //更新当前拍卖价格
    @UserLoginToken
    @PatchMapping("/{aid}/{addMoney}/{userId}/{userName}")
    public boolean patchNowPrice(@PathVariable("aid") long aid,
                                 @PathVariable("addMoney") int addMoney,
                                 @PathVariable("userId") long userId,
                                 @PathVariable("userName") String userName) {
        //此处最好更新为Redis数据库
        auctionRepository.updateAuctionNowPrice(addMoney, aid, userId, userName);
        return true;
    }

    //获取当前拍卖及时数据
    @UserLoginToken
    @GetMapping("/nowInfo/{aid}")
    public AuctionNowInfo partReturnNowPrice(@PathVariable("aid") long aid) {
        Auction tempAuction = findAuctionByAuctionId(aid);
        return new AuctionNowInfo(tempAuction.getNowPrice(), tempAuction.getNowWinId(), tempAuction.getNowWinName());
    }

    //根据ID获取拍卖信息
    @UserLoginToken
    @GetMapping("/{aid}")
    public Auction findAuctionByAuctionId(@PathVariable("aid") long aid) {
        return auctionRepository.findAuctionByAuctionId(aid);
    }

    //根据排序条件查找拍卖列表
    @UserLoginToken
    @GetMapping("/list/{orderName}/{asc}/{page}")
    public Page<Auction> findAllOrderBy(@PathVariable("orderName") String orderName,
                                        @PathVariable("asc") int asc,
                                        @PathVariable("page") int page) {
        Pageable pageable;
        if (asc == 1) {
            pageable = PageRequest.of(page - 1, RETURN_PAGE_SIZE, Sort.Direction.ASC, orderName);
        } else {
            pageable = PageRequest.of(page - 1, RETURN_PAGE_SIZE, Sort.Direction.DESC, orderName);
        }
        return auctionRepository.findAll(pageable);
    }

    //根据拍卖商品名查询拍卖列表
    @UserLoginToken
    @GetMapping("/ANC/{auctionNameContains}/{orderName}/{asc}/{page}")
    public Page<Auction> findAllByANC(@PathVariable("auctionNameContains") String auctionNameContains,
                                      @PathVariable("orderName") String orderName,
                                      @PathVariable("asc") int asc,
                                      @PathVariable("page") int page) {
        Sort.Direction direction;
        if (asc == 1)
            direction = Sort.Direction.ASC;
        else
            direction = Sort.Direction.DESC;
        Pageable pageable = PageRequest.of(page - 1, RETURN_PAGE_SIZE, direction, orderName);
        return auctionRepository.findAllByAuctionNameContains(pageable, auctionNameContains);
    }

    //根据拍卖tag查询拍卖列表
    @UserLoginToken
    @GetMapping("/tag/{auctionTag}/{orderName}/{asc}/{page}")
    public Page<Auction> findAllByTag(@PathVariable("auctionTag") String auctionTag,
                                      @PathVariable("orderName") String orderName,
                                      @PathVariable("asc") int asc,
                                      @PathVariable("page") int page) {
        Sort.Direction direction;
        if (asc == 1)
            direction = Sort.Direction.ASC;
        else
            direction = Sort.Direction.DESC;
        Pageable pageable = PageRequest.of(page - 1, RETURN_PAGE_SIZE, direction, orderName);
        return auctionRepository.findAllByAuctionTag(pageable, auctionTag);
    }

    //获取正在拍卖列表
    @UserLoginToken
    @GetMapping("/On/{page}")
    public Page<Auction> findAllByOn(@PathVariable("page") int page) {
        Pageable pageable = PageRequest.of(page - 1, RETURN_PAGE_SIZE, Sort.Direction.ASC, "auctionTimeStamp");
        long nowTimeStamp = new Date().getTime();
        long passTimeStamp = nowTimeStamp - 1000 * 60 * 15;//拍卖持续15分钟
        //根据拍卖起始时间来判断当前拍卖是否ON
        return auctionRepository.findAllByAuctionTimeStampBetween(pageable, passTimeStamp, nowTimeStamp);
    }

    //判断当前拍卖是否预约
    @UserLoginToken
    @GetMapping("/isApp/{aid}/{userId}")
    public boolean isAuctionAppointed(@PathVariable("aid") long auctionId,
                                      @PathVariable("userId") long userId) {
        return appointmentRepository.findAppointmentByAppointmentAuctionIdAndAppointmentUserId(auctionId, userId) != null;
    }

    //获取预约列表
    @UserLoginToken
    @GetMapping("/appointment/{userId}/{page}")
    public Page<Appointment> findAllAppointmentByUserId(@PathVariable("userId") long userId,
                                                        @PathVariable("page") int page) {
        Pageable pageable = PageRequest.of(page - 1, RETURN_PAGE_SIZE, Sort.Direction.ASC, "appointmentAuctionTimeStamp");
        return appointmentRepository.findAllByAppointmentUserId(userId, pageable);
    }

    //通过tag和拍卖名称查询列表
    @UserLoginToken
    @GetMapping("/ANCTAG/{auctionTag}/{auctionNameContains}/{orderName}/{asc}/{page}")
    public Page<Auction> findAllByANCTAG(@PathVariable("auctionTag") String auctionTag,
                                         @PathVariable("auctionNameContains") String auctionNameContains,
                                         @PathVariable("orderName") String orderName,
                                         @PathVariable("asc") int asc,
                                         @PathVariable("page") int page) {
        Sort.Direction direction;
        if (asc == 1)
            direction = Sort.Direction.ASC;
        else
            direction = Sort.Direction.DESC;

        Pageable pageable = PageRequest.of(page - 1, RETURN_PAGE_SIZE, direction, orderName);
        return auctionRepository.findAllByAuctionTagAndAuctionNameContains(pageable, auctionTag, auctionNameContains);
    }

    //根据卖家查询卖家的全部拍卖
    @UserLoginToken
    @GetMapping("/seller/{sellerId}/{page}")
    public Page<Auction> findAllBySellerId(@PathVariable("sellerId") long sellerId,
                                           @PathVariable("page") int page) {
        Pageable pageable = PageRequest.of(page - 1, RETURN_PAGE_SIZE);
        return auctionRepository.findAllBySellerId(pageable, sellerId);
    }


    //移除拍卖
    @UserLoginToken
    @DeleteMapping("{aid}")
    public void deleteAuctionById(@PathVariable("aid") long aid) {
        auctionRepository.deleteById(aid);
    }

    //取消预约，通过appId
    @UserLoginToken
    @DeleteMapping("/appointment/{aid}")
    public void deleteAppointmentById(@PathVariable("aid") long appId) {
        long auctionId = appointmentRepository.findAppointmentByAppointmentId(appId).getAppointmentAuctionId();
        appointmentRepository.decreaseAppointment(auctionId);
        appointmentRepository.deleteById(appId);
    }

    //取消预约--aucId+userId，在Show界面取消
    @UserLoginToken
    @DeleteMapping("/app/{aid}/{userId}")
    public void deleteAppointmentByAuctionIdAndUseId(@PathVariable("aid") long auctionId,
                                                     @PathVariable("userId") long userId) {
        appointmentRepository.decreaseAppointment(auctionId);
        appointmentRepository.deleteAppointmentByAU(auctionId, userId);
    }

    //删除拍卖
    @UserLoginToken
    @DeleteMapping("/{auctionId}")
    public void deleteAuctionByAuctionId(@PathVariable("auctionId") long auctionId) {
        auctionRepository.deleteById(auctionId);
    }

}















